import requests
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# 先将文件上传至文件存储（此存储为临时用，一小时后文件即会被删除）
upload_url = 'https://momodel.cn/pyapi/file/temp_api_file'
img_file = {'file': open('girl.jpeg', 'rb')}
img_file_name = requests.post(upload_url, files=img_file).json().get('temp_file_name')

# 拷贝云端AI卡通化应用的示例代码：https://momodel.cn/explore/60cd8e0d8d66a3a6efd82b67?type=app
base_url = "https://momodel.cn/pyapi/apps/run/"
app_id = "60cd8e0d8d66a3a6efd82b67"
input_dic = {"img": {"val": img_file_name, "type": "img"}}
output_dic = {"oimg": {"type": "img"}}
app_version = "dev"
payload = {"app": {"input": input_dic, "output": output_dic}, "version": app_version}
response = requests.post(base_url + app_id, json=payload)
print(response.json()) # 可以打印到输出窗口，观察一下回传的数据格式

tmp = response.json()
# print("https://momodel.cn/pyapi/file/temp_file/"+tmp["response"]["oimg"]) # 测试拼接的图片链接是否正确
r = requests.get("https://momodel.cn/pyapi/file/temp_file/" + tmp["response"]["oimg"]) # 按照拼接的链接地址，向云端请求回传已处理的图片

# 将网络获取的回传结果，存储成本地图片文件
with open("./girl_cartoon.jpg","wb") as f: 
    f.write(r.content)
f.close()

#显示转换前后照片
img_origin = mpimg.imread('girl.jpeg')
img_style = mpimg.imread('girl_cartoon.jpg')
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
ax1.imshow(img_origin)
ax2.imshow(img_style)
plt.show()